package com.squid.auth.service.login;


import cn.hutool.core.date.DateUtil;
import cn.hutool.jwt.JWT;
import com.squid.auth.model.req.LoginReq;
import com.squid.auth.model.resp.LoginResp;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;

import static com.squid.base.common.bean.TokenConstants.SECRET_TOKEN;

/**
 * 登录服务提示,
 * 双Token验证，accessToken，refreshToken
 * 一个是accessToken，用于进入页面的验证，时间较少，当过期后，需要刷新accessToken
 * 这个时候用refreshToken去刷新accessToken
 * 一般用这个是前端逻辑，后端提供token验证4
 *
 * @author jinhang1
 * @date 2024/05/09
 */
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Resource
    SimpleMeterRegistry simpleMeterRegistry;
    @Override
    public LoginResp login(LoginReq req) {
        // 获取当前时间
        Date now = DateUtil.date();
        // 计算七天后的时间
        Date oneDaysLater = DateUtil.offsetHour(now, 3);
        Date sevenDaysLater = DateUtil.offsetDay(now, 7);
        String username = req.getUsername();
        String password = req.getPassword();
        String accessToken = createToken(username, password,oneDaysLater,now);
        String refreshToken = createToken(username, password,sevenDaysLater,now);
        LoginResp build = LoginResp.builder().refreshToken(refreshToken).accessToken(accessToken).build();
        log.info("{}：登录成功", req.getUsername());
        return build;

    }

    @Override
    public void logout(LoginReq req) {
        log.info("{}：注销成功", req.getUsername());
    }

    @Override
    public String refreshToken(String req) {
        boolean validate = verifyToken(req);
        if (!validate) {
            JWT jwt = JWT.of(req);
            // 获取当前时间
            Date now = DateUtil.date();
            Date oneDaysLater = DateUtil.offsetDay(now, 1);
            // 计算七天后的时间
            String username = (String)jwt.getPayload("username");
            String password = (String)jwt.getPayload("password");
            return createToken(username, password,oneDaysLater,now);
        }else{
            return req;
        }
    }

    @Override
    public boolean verifyToken(String token) {
        return JWT.of(token).setKey(SECRET_TOKEN.getBytes()).validate(0);
    }

    private String createToken(String userName, String password,Date expireTime,Date notBeforeTime) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("username", userName);
        map.put("password", password);
        String sign = JWT.create()
                .setNotBefore(notBeforeTime)
                .setExpiresAt(expireTime)
                .addPayloads(map)
                .setKey(SECRET_TOKEN.getBytes())
                .sign();
        return sign;
    }
}
